package com.umfwechat.lightprogram.controller.selfdeploy;

import java.io.File;
import java.io.FileInputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


/**
 * 自助部署图片Controller
 * @author ChenFuLong 2017-05-16
 * @version 1.0
 */
@Controller
@RequestMapping("/merchantDeploy")
public class ShowImgController {

	private static Logger logger = LoggerFactory.getLogger(ShowImgController.class);
	
	/**
	 * 显示图片
	 * @author ChenFulong 2017-05-17
	 * @param session
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/showImg",produces="text/html;charset=UTF-8")
	public String showImg(HttpSession session,HttpServletRequest request, HttpServletResponse response) throws Exception{
		String imgName = request.getParameter("name");
		logger.info("----#---------#--获取服务器图片，开始--#---------#--" + imgName);
		FileInputStream in = null;
		ServletOutputStream out = null;
		try {
			File file = new File(imgName);
			if (!file.exists()) {
				in = new FileInputStream(request.getServletContext().getRealPath("/") + "styles/saasXcx/non.jpg");	//获取不到图片，则显示默认图片
			}else {
				in = new FileInputStream(imgName);
			}
			out = response.getOutputStream();
			byte tmp[] = new byte[1024];
			int i = 0;
			while ((i = in.read(tmp)) != -1) {
				out.write(tmp, 0, i);
			}
			out.flush();
		} catch (Exception e) {
			logger.info("----#---------#--获取服务器图片，异常--#---------#--" + e);
			throw e;
		} finally {
			if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                	 throw e;
                }
            }
		}
		logger.info("----#---------#--获取服务器图片，完成--#---------#--" + imgName);
		return null;
	}
	
	/**
	 * 生成图片，并返回URL
	 * @author ChenFuLong 2017-05-17
	 * @param in 图片流
	 * @param imageUrl 图片存储位置
	 * @param imgHttpUrl 返回的URL
	 * @return
	 */
	public static String getImgUrl(FileItem in, String imageUrl, String imgHttpUrl){
		logger.info("----#---------#--进入存储图片工具类，开始--#---------#--" + imageUrl + "--#---------#--" + imgHttpUrl);
		String path = imageUrl.substring(0, imageUrl.lastIndexOf("/"));
		try {
			File files = new File(path);
			if (!files.exists()) {
				files.mkdirs();
			}
			File file = new File(imageUrl);
			in.write(file);
			logger.info("----#---------#--存储图片到服务器成功--#---------#--");
			return imgHttpUrl + imageUrl;
		} catch (Exception e) {
			logger.info("----#---------#--存储图片到服务器失败--#---------#--" + e);
			return null;
		}
	}
}
